package com.fubowen.lepton.ui.container.children.bookmark.recycler

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SortedList
import com.fubowen.lepton.bean.BookmarkBean
import com.fubowen.lepton.databinding.FragmentBookmarkListItemBinding
import com.fubowen.lepton.helper.ViewHelper.setVisible
import com.fubowen.lepton.ui.container.children.bookmark.recycler.listener.OnItemClickListener


class BookmarkAdapter : RecyclerView.Adapter<BookmarkViewHolder>() {

    private var onItemClickListener: OnItemClickListener? = null
    private var dataSource: SortedList<BookmarkBean>? = null

    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.onItemClickListener = listener
    }

    fun setDataSource(list: SortedList<BookmarkBean>?) {
        dataSource = list
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): BookmarkViewHolder {

        val layoutInflater = LayoutInflater.from(viewGroup.context)
        val binding = FragmentBookmarkListItemBinding.inflate(layoutInflater, viewGroup, false)
        return BookmarkViewHolder(binding, this.onItemClickListener)
    }

    override fun getItemCount(): Int {
        return dataSource?.size() ?: 0
    }

    override fun onBindViewHolder(viewHolder: BookmarkViewHolder, position: Int) {
        dataSource?.let {
            val item = it.get(position)
            val binding = FragmentBookmarkListItemBinding.bind(viewHolder.itemView)
            binding.bookmarkItemSelectableGroup.setVisible(item.selectable)
            binding.bookmarkItemSelectable.isChecked = item.isSelected
            viewHolder.bind(item)
        }
    }
}
